package com.sprite.utils.conversion;

import java.math.BigInteger;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 其他类型转为 Date
 *
 * @author Jack
 * @since 1.0.0
 */
public class DateTimeConverters implements ConverterLoader {
    public static class DateTimeToLong implements Converter<Date, Long> {

        @Override
        public <K extends Date> Long convert(K source)
                throws ConversionException {
            return source.getTime();
        }

        @Override
        public Class<Date> getSourceClass() {
            return Date.class;
        }

        @Override
        public Class<Long> getTargetClass() {
            return Long.class;
        }

    }

    public static class StringToDateTime implements Converter<String, Date> {

        private SimpleDateFormat longFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        private SimpleDateFormat shortFormat = new SimpleDateFormat("yyyy-MM-dd");

        @Override
        public Date convert(String obj) throws ConversionException {
            if (obj == null) {
                return null;
            }
            obj = obj.trim();

            try {
                if (obj.length() < 19) {
                    return shortFormat.parse(obj);
                } else {
                    return longFormat.parse(obj);
                }
            } catch (ParseException e) {
                throw new ConversionException(e);
            }
        }

        @Override
        public Class<String> getSourceClass() {
            return String.class;
        }

        @Override
        public Class<Date> getTargetClass() {
            return Date.class;
        }

    }

    public static class BigIntegerToDateTime implements Converter<BigInteger, Date> {

        @Override
        public Date convert(BigInteger obj) throws ConversionException {
            if (obj == null) {
                return null;
            }

            return new Date(obj.longValue());
        }

        @Override
        public Class<BigInteger> getSourceClass() {
            return BigInteger.class;
        }

        @Override
        public Class<Date> getTargetClass() {
            return Date.class;
        }

    }

    @Override
    public void loadConverters() {
        Converts.loadContainedConverters(DateTimeConverters.class);
    }

}
